package com.zretc.file.service.impl;
import com.alibaba.nacos.common.utils.StringUtils;

import com.zretc.api.pojo.filesAndFriendModule.Files;

import com.zretc.api.pojo.filesAndFriendModule.dto.QueryFileListDTO;
import com.zretc.api.pojo.filesAndFriendModule.vo.FileListVO;
import com.zretc.api.pojo.recommendModule.Recommend;
import com.zretc.common.constant.WebConstant;
import com.zretc.common.entity.Pager;
import com.zretc.common.entity.R;
import com.zretc.common.entity.RespResult;
import com.zretc.file.dao.FileControlMapper;
import com.zretc.file.service.FileControlService;
import com.zretc.minio.service.FileStorageService;
import com.zretc.security.entity.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Slf4j
@Service
public class FileControlServiceimpl implements FileControlService {
    @Resource
    private FileStorageService fileStorageService;
    @Autowired
    private  FileControlMapper fileControlMapper;

    @Override
    public RespResult upload(MultipartFile file) {
        if(file == null || file.getSize() == 0){
            return R.fail(WebConstant.PARAM_ERROR_CODE2,WebConstant.PARAM_INVALID);
        }
        String uuid = UUID.randomUUID().toString();
           //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
           //查看文件后缀名
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
           //获取文件唯一标识码
        //String fileUUID = uuid + postfix;
           //获取文件名
        String fileName = uuid.replace("-", "");
        String url = null;
                //2.上传文件到minIO中
        try {
            url = fileStorageService.uploadFile("", fileName + postfix, file.getInputStream(),postfix);
            log.info("上传文件到MinIO中，url:{}",url);
            return R.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("FileControlServiceimpl-上传文件失败");
            return R.fail(600,"上传失败");
        }
    }

    @Override
    public RespResult downloadjianli(String url) {
        byte[] bytes = fileStorageService.downLoadFile(url);
        return R.success(bytes);

    }


    /**
     * 上传文件
     * @param multipartFile
     * @return
     */
    @Override
    public RespResult uploadFile(MultipartFile multipartFile) {
        //1.检查参数
        if(multipartFile == null || multipartFile.getSize() == 0){
            return R.fail(777,WebConstant.PARAM_INVALID);
        }
        String uuid = UUID.randomUUID().toString();
           //获取文件原始名称
        String originalFilename = multipartFile.getOriginalFilename();
           //查看文件后缀名
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
           //获取文件唯一标识码
        String fileUUID = uuid + StringUtils.DOT + postfix;
           //获取文件名
        String fileName = uuid.replace("-", "");
           //获取文件大小
        long size = multipartFile.getSize();

        String url = null;
        //2.上传文件到minIO中
        try {
            url = fileStorageService.uploadFile("", fileName + postfix, multipartFile.getInputStream(),postfix);
            log.info("上传文件到MinIO中，url:{}",url);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("FileControlServiceimpl-上传文件失败");
        }
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
       Files files =  new Files();
        files.setFileUUID(fileUUID);
        files.setUploaderId(loginUser.getUser().getId());
        files.setUploaderName(loginUser.getUser().getUser_name());
        files.setStatu(0);
        files.setUploadTime(new Date());
        files.setType(postfix);
        files.setSize(size);
        files.setDownloadCount(0);
        files.setUrl(url);
        files.setName(originalFilename);
        fileControlMapper.save(files);
        //4.返回结果
        return R.success("上传成功");
    }

    /**
     * 下载文件
     * @param fileUUID
     * @return
     */

    public RespResult downloadFile(String fileUUID) {
        //根据UUID获取文件url
        String url = fileControlMapper.searchUrlByFileUUID(fileUUID);
        //根据UUID获取下载次数以及加1
        int downloadCount = fileControlMapper.searchCountByFileUUID(fileUUID)+1;
        //更新下载次数
        Files updateCount = new Files();
        updateCount.setDownloadCount(downloadCount);
        updateCount.setFileUUID(fileUUID);
        fileControlMapper.updateCount(updateCount);
        return R.success(url);
    }

    /**
     * 文件分页查询
     * @param
     * @return
     */

    @Override
    public Map<String,Object> fileList(Integer pageNum, Integer pageSize,String typename,String keyword) {
        Pager pager = new Pager(fileControlMapper.getCount(), pageNum,pageSize);
        ArrayList<FileListVO> fileListVOS = fileControlMapper.queryByPage(pager.getStartIndex(), pager.getPageSize(),typename,keyword);
        HashMap<String,Object> map = new HashMap<>();
        map.put("pager",pager);
        map.put("list",fileListVOS);
        return map;
    }
//
//    /**
//     * 文件删除
//     * @param fileUUID
//     */
//    @Override
//    public void delete(String fileUUID) {
//        //根据UUID获取文件url
//        String url = fileControlMapper.searchUrlByFileUUID(fileUUID);
//        //删除MinIO中的文件
//        fileStorageService.delete(url);
//        log.info("删除MinIO中的文件url:{}",url);
//        //删除数据库数据
//        fileControlMapper.deleteFile(fileUUID);
//    }
}
